package com.qc.controller.merchant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qc.common.ImageUtils;
import com.qc.common.QiNiuUtil;
import com.qc.common.StringUtil;
import com.qc.entity.BusinessInformEntity;
import com.qc.entity.BusinessJob;
import com.qc.entity.BusinessPeopleVo;
import com.qc.entity.BusinessReceive;
import com.qc.entity.Coupon;
import com.qc.entity.MerchantEntity;
import com.qc.pageUtil.page.page.Page;
import com.qc.pageUtil.page.page.PageModel;
import com.qc.pageUtil.page.page.PageModelList;
import com.qc.pageUtil.page.vo.NewsAndNav;
import com.qc.service.BusinessInformService;
import com.qc.service.BusinessJobService;
import com.qc.service.BusinessPeopleService;
import com.qc.service.BusinessReceiveService;
import com.qc.service.CouponService;
import com.qc.service.MerchantService;

import net.sf.json.JSONObject;


@SuppressWarnings({ "unchecked", "rawtypes" })
@Controller
@RequestMapping("/merchant")
public class BusinessInformController {
    
    @Resource(name="businessInformService")
    private BusinessInformService businessInformService;
    
    @Resource(name="businessJobService")
    private BusinessJobService businessJobService;
    
    @Resource(name="couponService")
    private CouponService couponService;
    
    @Resource(name="businessReceiveService")
    private BusinessReceiveService businessReceiveService;
    
    @Resource(name="businessPeopleService")
    private BusinessPeopleService businessPeopleService;
    
    @Resource(name="merchantService")
    private MerchantService merchantService;
    
    /**
     * 商家发布页
     * @param request
     * @return
     */
    @RequestMapping(value = "/toRelease", produces = "text/html;charset=UTF-8")
    public ModelAndView toRelease(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/release");
        
        long shopId = Long.parseLong(request.getParameter("shopId"));
        
        BusinessInformEntity informEntity = businessInformService.getBusinessInformId(shopId);
        
        MerchantEntity merchantEntity =  merchantService.getMerchantId(shopId);
        
        mav.addObject("informEntity",informEntity);
        mav.addObject("merchantEntity",merchantEntity);

        return mav;
    }
            
    /**
     * 商家发布信息
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "/toSaveRelease", produces = "text/html;charset=UTF-8")
    public ModelAndView toSaveRelease(HttpServletRequest request,@RequestParam("file") CommonsMultipartFile file) throws IOException {
        
    	long shopId = Long.parseLong(request.getParameter("shopId"));
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        long bId = Long.parseLong(request.getParameter("bId"));
        String image = request.getParameter("image");
        
        ModelAndView mav = new ModelAndView("redirect:/merchant/toRelease.do?shopId="+shopId);
        
        String url = request.getSession().getServletContext().getRealPath("/")+("/fileImage");
        
        BusinessInformEntity informEntity = businessInformService.getBusinessInformId(shopId);
        
        
        String fileName = file.getOriginalFilename();
        if (StringUtil.isNotEmpty(fileName)) {
        	//目录不存在 新建一个
            File f1=new File(url); 
            if(!f1.isDirectory()) {
                f1.mkdir();
            }
            //创建时间参数
            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");// 文件重命名
            String namefile = bartDateFormat.format(new Date());
            
            InputStream stream = file.getInputStream();// 把文件读入
            
            //图片名字
            fileName = namefile + fileName.substring(fileName.lastIndexOf("."));// 保存文件路径和文件名
            OutputStream bos = new FileOutputStream(url + "/" + fileName);// 建立一个上传文件的路径
            int bytesRead = 0;
            byte[] buffer = new byte[10240];
            while ((bytesRead = stream.read(buffer, 0, 10240)) != -1) {
                // 将文件写入服务器
                bos.write(buffer, 0, bytesRead);
            }
            bos.close();
            stream.close();
            
            String path = url + "/" + fileName;
            
            ImageUtils.scale(path, path, 2, true);
            
            try {
                QiNiuUtil.upload(path, "web_dev_14_qiniu_"+fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            informEntity.setImage("web_dev_14_qiniu_"+fileName);
        
        }else{
        	informEntity.setImage(image);
        }
        informEntity.setTitle(title);
        informEntity.setContent(content);
        informEntity.setShopId(shopId);
        if (bId != 0) {
            informEntity.setbId(bId);
            
            businessInformService.updateBusinessInformId(informEntity);
        }else {
            businessInformService.saveBusinessInform(informEntity);
        }
        
        return mav;
    }
    
    @RequestMapping(value = "/toFileUpload", produces = "text/html;charset=UTF-8")
    public void toFileUpload(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException,FileUploadException {
        
        response.setCharacterEncoding("utf-8");  
        PrintWriter out = response.getWriter();
        
        String savePath = request.getSession().getServletContext().getRealPath("/")+("/fileImage/");

        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // 最大文件大小
        long maxSize = 1000000;

        response.setContentType("text/html; charset=UTF-8");
        JSONObject obj = new JSONObject();

        if (!ServletFileUpload.isMultipartContent(request)) {
            out.print("请选择文件");  
            out.close();  
            return;
        }
        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            uploadDir.mkdirs();
        }

        String dirName = request.getParameter("dir");
        
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");


        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        
        Iterator item = multipartRequest.getFileNames();
        while (item.hasNext()) {

            String fileName = (String) item.next();

            MultipartFile file = multipartRequest.getFile(fileName);
            
            // 检查文件大小
            if (file.getSize() > maxSize) {

                out.print("上传文件大小超过限制");  
                out.close();  
                return;

            }
            
            // 检查扩展名
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();

            if (!Arrays. asList(extMap.get(dirName).split(",")).contains(fileExt)) {

                out.print("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");  
                out.close();  
                return;
            }
            
            //创建时间参数
            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");// 文件重命名
            String namefile = bartDateFormat.format(new Date());
            
            InputStream stream = file.getInputStream();// 把文件读入
            
            //图片名字
            fileName = namefile + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));// 保存文件路径和文件名
            OutputStream bos = new FileOutputStream(savePath + "/" + fileName);// 建立一个上传文件的路径
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                // 将文件写入服务器
                bos.write(buffer, 0, bytesRead);
            }
            bos.close();
            stream.close();
            
            String path = savePath + "/" + fileName;
            
            ImageUtils.scale(path, path, 2, true);
            
            try {
                QiNiuUtil.upload(path, "web_dev_14_qiniu_"+fileName);
            } catch (Exception e) {
                out.print("上传文件失败");  
                out.close();  
                return;
            }
            
            obj.put("error", 0);    
            obj.put("url", "http://oi7u997mi.bkt.clouddn.com/web_dev_14_qiniu_"+fileName);    
              
            out.print(obj.toString());  
            out.close();
        }
    }
    
    
    /**
     * 商家发布招聘
     * @param request
     * @return
     */
    @RequestMapping(value = "/toZpInform", produces = "text/html;charset=UTF-8")
    public ModelAndView toZpInform(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/zp-inform");
        
        long shopId = Long.parseLong(request.getParameter("shopId"));
        
        BusinessJob businessJob = businessJobService.getBusinessJobId(shopId);
        
        mav.addObject("shopId",shopId);
        mav.addObject("businessJob",businessJob);
        
        return mav;
    }
    
    /**
     * 添加招聘 发布信息
     */
    @RequestMapping(value = "/toSaveZpInform", produces = "text/html;charset=UTF-8")
    public ModelAndView toSaveZpInform(HttpServletRequest request,BusinessJob businessJob){
    	
    	ModelAndView mav = new ModelAndView("redirect:/merchant/toZpInform.do?shopId="+businessJob.getShopId());
    	
    	BusinessJob businessJob2 = businessJobService.getBusinessJobId(businessJob.getShopId());
    	if (businessJob2.getShopId() != 0) {
    		
    		businessJob2.setAge(businessJob.getAge());
    		businessJob2.setAgeTwo(businessJob.getAgeTwo());
    		businessJob2.setAppearance(businessJob.getAppearance());
    		businessJob2.setContent(businessJob.getContent());
    		businessJob2.setEndDate(businessJob.getEndDate());
    		businessJob2.setNum(businessJob.getNum());
    		businessJob2.setSchool(businessJob.getSchool());
    		businessJob2.setSecHeight(businessJob.getSecHeight());
    		businessJob2.setSecHeightTwo(businessJob.getSecHeightTwo());
    		businessJob2.setSex(businessJob.getSex());
    		businessJob2.setSkill(businessJob.getSkill());
    		businessJob2.setStartDate(businessJob.getStartDate());
    		businessJob2.setTitle(businessJob.getTitle());

    		businessJobService.updateBusinessJobId(businessJob2);
    		
    	}else {
    		businessJobService.saveBusinessJob(businessJob);
    	}
    	
    	return mav;
    }
    
    /**
     * 招聘 应聘人员
     * @param request
     * @return
     */
    @RequestMapping(value = "/toPeople", produces = "text/html;charset=UTF-8")
    public ModelAndView toPeople(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/people");
        
        String shopId = request.getParameter("shopId");
        
        mav.addObject("shopId",shopId);

        return mav;
    }
    
    /**
     * 招聘 列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/toListAllPeople", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String toListAllPeople(HttpServletRequest request) {
        
    	String nickName = request.getParameter("name");
        
        long shopId = Long.parseLong(request.getParameter("shopId"));
        //当前页面
        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        //每页显示多少条
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        
        int state = Integer.parseInt(request.getParameter("state"));
        
        //根据条件总数
        int recordCount = businessPeopleService.getListBusinessJobVoCount(shopId,nickName,state);
        
        //根据条件查询当前页数据
        List<BusinessPeopleVo> list = businessPeopleService.getAllBusinessPeople(shopId,nickName, state,pageNo, pageSize);
        
        //分页查询公共类
        Page<BusinessPeopleVo> page = new Page<BusinessPeopleVo>(pageNo, recordCount,pageSize);
        page.setList(list);//设置结果集  
        PageModelList<BusinessPeopleVo> pageModel = new PageModelList<BusinessPeopleVo>(page, "#", PageModel.NUM_MODEL,"doPage","1");//设置页码显示类型  
        //4 组装带翻页导航功能的对象
        NewsAndNav  objs = new NewsAndNav(list, pageModel.getPageModel());
        
        return JSONObject.fromObject(objs).toString();
        
    }
    
    /**
     * 招聘 查看页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toPeopleInf", produces = "text/html;charset=UTF-8")
    public ModelAndView toPeopleInf(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/people_inf");
        
        long bId = Long.parseLong(request.getParameter("id"));
        
        BusinessPeopleVo businessPeople = businessPeopleService.getBusinessPeopleVoId(bId);
        
        mav.addObject("businessPeople",businessPeople);

        return mav;
    }
    
    /**
     * 招聘查看 通过拒绝 操作
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/updatePeopleId")
    @ResponseBody
    public int updatePeopleId(HttpServletRequest request,HttpServletResponse response) {
    	long bId = Long.parseLong(request.getParameter("id"));
    	int state = Integer.parseInt(request.getParameter("state"));
    	
    	int flag = businessPeopleService.updatePeopleId(bId, state);
    	
        return flag;
    }
    
    @RequestMapping(value = "/toSpePeopleInf", produces = "text/html;charset=UTF-8")
    public ModelAndView toSpePeopleInf(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/spe_people_inf");
        
        String shopId = request.getParameter("shopId");
        
        mav.addObject("shopId",shopId);

        return mav;
    }
    
    /**
     * 优惠卷 发布页
     * @param request
     * @return
     */
    @RequestMapping(value = "/toCoupon", produces = "text/html;charset=UTF-8")
    public ModelAndView toCoupon(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/yhj");
        
        String shopId = request.getParameter("shopId");
        
        mav.addObject("shopId",shopId);
        return mav;
    }
    
    /**
     * 优惠券添加
     * @param request
     * @param coupon
     * @return
     */
    @RequestMapping(value = "/toSaveCoupon", produces = "text/html;charset=UTF-8")
    public ModelAndView toSaveCoupon(HttpServletRequest request,Coupon coupon){
        ModelAndView mav = new ModelAndView("redirect:/merchant/toCouponYhjHistory.do");
        
        String shopId = request.getParameter("shopId");
        int tiyan_num = Integer.parseInt(request.getParameter("tiyan_num"));
        if (tiyan_num != 0) {
        	
        	coupon.setNum(tiyan_num);
        }
        
        coupon.setNumNumber(coupon.getNum());
        
        couponService.saveCoupon(coupon);
        
        mav.addObject("shopId",shopId);
        
        return mav;
    }
    
    /**
     * 优惠券列表展示
     * @param request
     * @return
     */
    @RequestMapping(value = "/toCouponYhjHistory", produces = "text/html;charset=UTF-8")
    public ModelAndView toCouponYhjHistory(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/yhj-history");
        
        String shopId = request.getParameter("shopId");
        
        mav.addObject("shopId",shopId);
        return mav;
    }
    
    
    /**
     * 优惠券 数据展示
     * @param request
     * @return
     */
    @RequestMapping(value = "/toListAllCoupon", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String toListAllCoupon(HttpServletRequest request) {
        
        String name = request.getParameter("name");
        
        long shopId = Long.parseLong(request.getParameter("shopId"));
        //当前页面
        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        //每页显示多少条
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        
        //根据条件总数
        int recordCount = couponService.getListCouponCount(name, shopId);
        
        //根据条件查询当前页数据
        List<Coupon> list = couponService.getAllCoupon(name, shopId, pageNo, pageSize);
        
        //分页查询公共类
        Page<Coupon> page = new Page<Coupon>(pageNo, recordCount,pageSize);
        page.setList(list);//设置结果集  
        PageModelList<Coupon> pageModel = new PageModelList<Coupon>(page, "#", PageModel.NUM_MODEL,"doPage","1");//设置页码显示类型  
        //4 组装带翻页导航功能的对象
        NewsAndNav  objs = new NewsAndNav(list, pageModel.getPageModel());
        
        return JSONObject.fromObject(objs).toString();
        
    }
    
    @RequestMapping(value = "/updateCouponState")
    @ResponseBody
    public int updateCouponState(HttpServletRequest request,HttpServletResponse response) {
    	long bId = Long.parseLong(request.getParameter("id"));
    	String state = request.getParameter("state");
    	
    	int flag = couponService.updateState(bId, state);
        return flag;
    }
    
    /**
     * 商家优惠券 使用记录
     * @param request
     * @return
     */
    @RequestMapping(value = "/toCouponYhjUsed", produces = "text/html;charset=UTF-8")
    public ModelAndView toCouponYhjUsed(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/yhj-used");
        
        String shopId = request.getParameter("shopId");
        
        mav.addObject("shopId",shopId);
        
        return mav;
    }
    
    @RequestMapping(value = "/toListAllCouponReceive", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String toListAllCouponReceive(HttpServletRequest request) {
        
        long shopId = Long.parseLong(request.getParameter("shopId"));
        //当前页面
        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        //每页显示多少条
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        
        //根据条件总数
        int recordCount = businessReceiveService.getListReceiveCount(shopId);
        
        //根据条件查询当前页数据
        List<BusinessReceive> list = businessReceiveService.listAllReceive(shopId, pageNo, pageSize);
        
        //分页查询公共类
        Page<BusinessReceive> page = new Page<BusinessReceive>(pageNo, recordCount,pageSize);
        page.setList(list);//设置结果集  
        PageModelList<BusinessReceive> pageModel = new PageModelList<BusinessReceive>(page, "#", PageModel.NUM_MODEL,"doPage","1");//设置页码显示类型  
        //4 组装带翻页导航功能的对象
        NewsAndNav  objs = new NewsAndNav(list, pageModel.getPageModel());
        
        return JSONObject.fromObject(objs).toString();
        
    }
    
    /**
     * 优惠券核销 
     * @param request
     * @return
     */
    @RequestMapping(value = "/toYhjhexiao", produces = "text/html;charset=UTF-8")
    public ModelAndView toYhjhexiao(HttpServletRequest request){
        ModelAndView mav = new ModelAndView("/business/yhj-hexiao");
        
        long shopId = Long.parseLong(request.getParameter("shopId"));
        
        mav.addObject("shopId",shopId);

        return mav;
    }
    
    /**
     * 根据优惠券编号修改 优惠券使用状态 
     */
    @RequestMapping(value = "/toUpdateDestroy")
    @ResponseBody
    public int toUpdateDestroy(HttpServletRequest request,HttpServletResponse response) {
    	
    	String cNumber = request.getParameter("couponNumber");
    	long shopId = Long.parseLong(request.getParameter("shopId"));
    	
    	int flag = 0;
    	
    	String[] number = cNumber.split(",");
    		
		for (String couponNumber : number) {
    		
    		BusinessReceive receive = businessReceiveService.getCouponNumber(shopId, couponNumber);
    		if (StringUtil.isNotEmpty(receive.getCouponNumber())) {
    			
    			receive.setState(1);
    			receive.setCouponId(receive.getCouponId());
    			
    			flag = businessReceiveService.updateBusinessReceiveState(receive);
    			
    			return flag;
    		}else{
    			flag = 2;
    		}
    	}
    	
    	return flag;
    	
    }
    
    
    
    
}
